package com.burst.reptile.modular.zp.service.impl;

import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.exception.CustomException;
import com.burst.reptile.common.exception.job.TaskException;
import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.common.utils.file.ImgUtils;
import com.burst.reptile.common.utils.job.CronUtils;
import com.burst.reptile.common.utils.zp.HtmlUtils;
import com.burst.reptile.framework.config.CrawlerConfig;
import com.burst.reptile.framework.security.service.TokenService;
import com.burst.reptile.framework.tencent.CosPutObject;
import com.burst.reptile.modular.api.form.QueryResForm;
import com.burst.reptile.modular.api.form.ResourcesForm;
import com.burst.reptile.modular.api.vo.PublishRes;
import com.burst.reptile.modular.monitor.entity.SysJob;
import com.burst.reptile.modular.monitor.service.ISysJobService;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.zp.entity.ZpCity;
import com.burst.reptile.modular.zp.entity.ZpLabel;
import com.burst.reptile.modular.zp.entity.ZpResources;
import com.burst.reptile.modular.zp.mapper.ZpLabelMapper;
import com.burst.reptile.modular.zp.mapper.ZpResourcesMapper;
import com.burst.reptile.modular.zp.service.IZpCityService;
import com.burst.reptile.modular.zp.service.IZpResourcesService;
import com.hankcs.hanlp.HanLP;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * <p>
 * 资源列表 服务实现类
 * </p>
 *
 * @author wujin
 * @since 2020-06-15
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ZpResourcesServiceImpl extends ServiceImpl<ZpResourcesMapper, ZpResources> implements IZpResourcesService {

	private final TokenService tokenService;

	private final ZpLabelMapper labelMapper;

	private final CosPutObject cosPutObject;

	private final ISysJobService jobService;

	private final IZpCityService cityService;

	@Override
	public List<ZpResources> listByRecId(List<Long> articleIds) {
		return this.list(new QueryWrapper<ZpResources>().in("article_id", articleIds));
	}

	@Override
	public Page<ZpResources> pageList(Page<ZpResources> page, ZpResources zpResources) {
		Integer columnId = zpResources.getColumnId();
		String rec = zpResources.getRec();
		String city = zpResources.getCity();
		Integer sortt = zpResources.getSortt();
		QueryWrapper<ZpResources> queryWrapper = new QueryWrapper<ZpResources>();
		if (StrUtil.isNotEmpty(rec)) { // 推荐
			queryWrapper.eq("rec", rec);
		}
		if (StrUtil.isNotEmpty(city)) { // 站点
			queryWrapper.eq("city", city);
		}
		if (ToolUtil.isNotEmpty(columnId)) { // 栏目
			queryWrapper.eq("column_id", columnId);
			if (columnId > 1) {
				queryWrapper.eq("city", tokenService.getCitySite());
			}
		}
		String county = zpResources.getCounty();
		if (StrUtil.isNotEmpty(county)) { // 区县
			queryWrapper.eq("county", county);
		}
		Integer formatId = zpResources.getFormatId();
		if (ToolUtil.isNotEmpty(formatId)) { // 业态
			queryWrapper.eq("format_id", formatId);
		}
		Integer serviceItems = zpResources.getServiceItems();
		if (ToolUtil.isNotEmpty(serviceItems)) { // 服务类型
			queryWrapper.eq("service_items", serviceItems);
		}
		Long userId = zpResources.getUserId();
		if (ToolUtil.isNotEmpty(userId)) { // 作者
			queryWrapper.eq("user_id", userId);
		}
		queryWrapper.select("article_id", "title", "summary", "county", "cover_image", "cover_video", "picture_set",
				"video_etag", "video_url", "posters", "draft", "article_type", "column_id", "format_id", "read_size",
				"vote_size", "collect_size", "user_id", "create_time", "update_time", "timing_time");
		queryWrapper.eq("draft", "0"); // 已发布
		if(ToolUtil.isEmpty(sortt) || sortt == 0) {
			queryWrapper.orderByDesc("create_time", "vote_size", "read_size");
		}else if(ToolUtil.isNotEmpty(sortt) && sortt == 1){
			queryWrapper.orderByDesc("read_size");
		}else if(ToolUtil.isNotEmpty(sortt) && sortt == 2) {
			queryWrapper.orderByDesc("vote_size");
		}
		return this.page(page, queryWrapper);
	}

	@Override
	public Page<ZpResources> pageListByRec(int pageNum, int limit, Long userId) {
		Page<ZpResources> page = new Page<>(pageNum, limit);
		return this.baseMapper.pageListByRec(page, userId);
	}

	@Override
	public int incrRead(Long articleId) {
		return this.baseMapper.incrRead(articleId);
	}

	@Override
	@Transactional
	public PublishRes add(ResourcesForm resources) {
		ZpResources zpResources = new ZpResources();
		Long articleId = resources.getArticleId();
		if (ToolUtil.isNotEmpty(articleId)) {
			ZpResources byId = this.getById(articleId);
			if (ToolUtil.isNotEmpty(byId) && byId.getUserId().equals(SecurityUtils.getLoginUserId())) {
				this.removeById(articleId);
			}
		}
		BeanUtil.copyProperties(resources, zpResources);
		this.wrap(zpResources);
		// 保存
		boolean save = this.save(zpResources);
		if (!save) {
			throw new CustomException("发布失败");
		}
		addTags(zpResources.getTags());
		return PublishRes.builder().id(zpResources.getArticleId()).title(zpResources.getTitle())
				.draft(zpResources.getDraft()).build();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public PublishRes update(ResourcesForm resources) {
		ZpResources byId = this.getById(resources.getArticleId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("更新的资源不存在失败");
		}
		Long userId = byId.getUserId();
		Long loginUserId = SecurityUtils.getLoginUserId();
		if (!userId.equals(loginUserId)) {
			throw new CustomException("禁止操作");
		}
		ZpResources zpResources = new ZpResources();
		BeanUtil.copyProperties(resources, zpResources);
		this.wrap(zpResources);
		boolean updateById = this.updateById(zpResources);
		if (!updateById) {
			throw new CustomException("更新失败");
		}
		addTags(zpResources.getTags());
		SysJob job = jobService.getById(byId.getArticleId());
		if (ToolUtil.isNotEmpty(job)) {
			try {
				jobService.deleteJob(job);
			} catch (SchedulerException e) {
				log.error("移除定时任务失败：{}", e);
			}
		}
		return PublishRes.builder().id(zpResources.getArticleId()).title(zpResources.getTitle())
				.draft(zpResources.getDraft()).build();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public PublishRes regularRelease(ResourcesForm resources) throws SchedulerException, TaskException {
		ZpResources zpResources = new ZpResources();
		Long articleId = resources.getArticleId();
		if (ToolUtil.isNotEmpty(articleId)) {
			ZpResources byId = this.getById(articleId);
			if (ToolUtil.isNotEmpty(byId) && byId.getUserId().equals(SecurityUtils.getLoginUserId())) {
				this.removeById(articleId);
			}
		}
		BeanUtil.copyProperties(resources, zpResources);
		this.wrap(zpResources);
		// 保存
		boolean save = this.save(zpResources);
		if (!save) {
			throw new CustomException("发布失败");
		}
		addTags(zpResources.getTags());
		Long arId = zpResources.getArticleId();
		// 创建定时任务
		SysJob job = new SysJob();
		job.setJobId(arId);
		job.setJobName("定时发布信息【" + zpResources.getTitle() + "】");
		job.setJobGroup(Constants.PUBLISH);
		job.setInvokeTarget("antsTask.timingPublish(" + arId + "L)");
		job.setCronExpression(CronUtils.getCronByOnce(zpResources.getTimingTime()));
		job.setMisfirePolicy("2");
		job.setConcurrent("1");
		job.setJobStatus("0");
		job.setRemark("定时发布信息【" + zpResources.getTitle() + "】,信息编号为【】" + arId);
		jobService.insertJob(job);
		return PublishRes.builder().id(arId).title(zpResources.getTitle()).draft(zpResources.getDraft()).build();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public PublishRes regularReleaseEdit(ResourcesForm resources) throws SchedulerException, TaskException {
		ZpResources byId = this.getById(resources.getArticleId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("更新的资源不存在失败");
		}
		Long userId = byId.getUserId();
		Long loginUserId = SecurityUtils.getLoginUserId();
		if (!userId.equals(loginUserId)) {
			throw new CustomException("禁止操作");
		}
		ZpResources zpResources = new ZpResources();
		BeanUtil.copyProperties(resources, zpResources);
		this.wrap(zpResources);
		zpResources.setDraft("3");
		boolean updateById = this.updateById(zpResources);
		if (!updateById) {
			throw new CustomException("更新失败");
		}
		addTags(zpResources.getTags());
		SysJob job = jobService.getById(byId.getArticleId());
		if (ToolUtil.isNotEmpty(job)) {
			job.setInvokeTarget("antsTask.timingPublish(" + zpResources.getArticleId() + "L)");
			job.setCronExpression(CronUtils.getCronByOnce(zpResources.getTimingTime()));
			jobService.updateJob(job);
		} else {
			// 创建定时任务
			SysJob cjob = new SysJob();
			cjob.setJobId(zpResources.getArticleId());
			cjob.setJobName("定时发布信息【" + zpResources.getTitle() + "】");
			cjob.setJobGroup(Constants.PUBLISH);
			cjob.setInvokeTarget("antsTask.timingPublish(" + zpResources.getArticleId() + "L)");
			cjob.setCronExpression(CronUtils.getCronByOnce(zpResources.getTimingTime()));
			cjob.setMisfirePolicy("2");
			cjob.setConcurrent("1");
			cjob.setJobStatus("0");
			cjob.setRemark("定时发布信息【" + zpResources.getTitle() + "】,信息编号为【】" + zpResources.getArticleId());
			jobService.insertJob(cjob);
		}
		return PublishRes.builder().id(zpResources.getArticleId()).title(zpResources.getTitle())
				.draft(zpResources.getDraft()).build();
	}

	@Override
	public Page<ZpResources> search(int pageNum, int limit, String keyword, List<String> ik) {
		Page<ZpResources> page = new Page<>(pageNum, limit);
		if (StrUtil.isNotEmpty(keyword)) {
			QueryWrapper<ZpResources> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("draft", "0").and(i -> i.eq("city", tokenService.getCitySite()));
			if (ToolUtil.isNotEmpty(ik)) {
				queryWrapper.and(i -> {
					for (String string : ik) {
						i.like("title", string).or().like("summary", string).or().like("tags", string).or()
								.like("keywords", string);
					}
				});
			} else {
				queryWrapper.and(i -> i.like("title", keyword).or().like("summary", keyword).or().like("tags", keyword)
						.or().like("keywords", keyword));
			}
			queryWrapper.orderByDesc("update_time");
			return this.page(page, queryWrapper);
		}
		return new Page<>(pageNum, limit);
	}

	@Override
	public Page<ZpResources> myPageList(Page<ZpResources> page, QueryResForm query) {
		return this.baseMapper.myPageList(page, query);
	}

	/**
	 * 数据封装
	 * 
	 * @param zpResources
	 */
	private void wrap(ZpResources zpResources) {
		String content = zpResources.getContent();
		String contentText = zpResources.getContentText();
		String title = zpResources.getTitle();
		String contentText2 = zpResources.getContentText();
		if (contentText2.length() >= 300) {
			zpResources.setRec("1");
		}
		// 经营业态
		Integer formatId = zpResources.getFormatId();
		if (ToolUtil.isNotEmpty(formatId) && formatId == -1) {
			zpResources.setFormatId(null);
		}
		// 区域站点
		String county = zpResources.getCounty();
		if (StrUtil.equals(county, "-1")) {
			zpResources.setCounty(null);
		}
		String keystr = title;
		if (StrUtil.isNotEmpty(contentText)) {
			// 文章摘要
			String summary = HanLP.getSummary(contentText, 130);
			zpResources.setSummary(summary);
			keystr += contentText;
		}
		// 关键词
		List<String> keyWordsList = HanLP.extractKeyword(keystr, 50);
		String keywords = StrUtil.sub(StrUtil.join(",", keyWordsList), 0, 500);
		zpResources.setKeywords(keywords);
		// 文章图片
		List<String> imgs = HtmlUtils.getImgs(content);
		// 文章视频
		List<String> videos = HtmlUtils.getVideo(content);
		if (ToolUtil.isNotEmpty(videos)) {
			if (videos.size() > 1) {
				throw new CustomException("最多上传一个视频");
			}
			zpResources.setVideoUrl(JSONObject.toJSONString(new HashSet<>(videos)));
			// 文章视频Etag
			List<String> videoEtag = HtmlUtils.getVideoEtag(content);
			if (ToolUtil.isNotEmpty(videoEtag)) {
				zpResources.setVideoEtag(JSONObject.toJSONString(new HashSet<>(videoEtag)));
			}

			// 文章视频
			List<String> coverVideos = HtmlUtils.getVideoPoster(content);
			if (ToolUtil.isNotEmpty(coverVideos)) {
				zpResources.setCoverVideo(coverVideos.get(0));
				zpResources.setPosters(JSONObject.toJSONString(new HashSet<>(coverVideos)));
			}
		} else if (ToolUtil.isNotEmpty(imgs)) {
			Set<String> hashSet = new HashSet<>(imgs);
			String bucketName = CrawlerConfig.getBucketName();
			if (hashSet.size() > 3) {
				List<String> pic = new ArrayList<>();
				int i = 0;
				for (String string : hashSet) {
					if (i > 3) {
						break;
					}
					String destImageFile = CrawlerConfig.getImgCoverPath() + IdUtil.simpleUUID() + ".jpg";
					String[] split = StrUtil.splitToArray(string, "/");
					String uploadPath = CrawlerConfig.getUploadPath();
					// 上传文件路径
					String fileName = uploadPath + File.separator + split[split.length - 1];
					if (ToolUtil.isNotEmpty(split) && FileUtil.isFile(fileName)) {
						ImgUtils.imgcompressloc(fileName, 200, 135, destImageFile);
					} else {
						ImgUtils.imgcompress(string, 200, 135, destImageFile);
					}
					String imgFileName = IdUtil.simpleUUID() + ".jpg";
					String imgkey = Constants.IMG_KEY + imgFileName;
					cosPutObject.localPut(destImageFile, bucketName, imgkey);
					pic.add(Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/" + Constants.IMG_KEY
							+ imgFileName);
					i++;
				}
				zpResources.setPictureSet(JSONObject.toJSONString(new HashSet<>(pic)));
			} else {
				String destImageFile = CrawlerConfig.getImgCoverPath() + IdUtil.simpleUUID() + ".jpg";
				String string = imgs.get(0);
				String[] split = StrUtil.splitToArray(string, "/");
				String uploadPath = CrawlerConfig.getUploadPath();
				// 上传文件路径
				String fileName = uploadPath + File.separator + split[split.length - 1];
				if (ToolUtil.isNotEmpty(split) && FileUtil.isFile(fileName)) {
					ImgUtils.imgcompressloc(fileName, 200, 135, destImageFile);
				} else {
					ImgUtils.imgcompress(string, 200, 135, destImageFile);
				}
				String imgFileName = IdUtil.simpleUUID() + ".jpg";
				String imgkey = Constants.IMG_KEY + imgFileName;
				cosPutObject.localPut(destImageFile, bucketName, imgkey);
				zpResources.setCoverImage(Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/"
						+ Constants.IMG_KEY + imgFileName); // 文章封面
			}
		}
		
		Integer columnId = zpResources.getColumnId();
		if (columnId == 1) {
			// 发布站点
			zpResources.setCity(tokenService.getCitySite());
		}
		zpResources.setUserId(SecurityUtils.getLoginUserId());
	}

	/**
	 * 新增或更新标签
	 * 
	 * @param tags
	 */
	private void addTags(String tags) {
		if (StrUtil.isNotEmpty(tags)) {
			List<String> parseArray = JSONObject.parseArray(tags, String.class);
			for (String string : parseArray) {
				ZpLabel one = labelMapper.selectOne(new QueryWrapper<ZpLabel>().eq("label_name", string));
				if (ToolUtil.isNotEmpty(one)) { // 累计标签热度
					one.setLabelHeat(one.getLabelHeat() + 1);
					labelMapper.updateById(one);
				} else {// 新增文章标签
					ZpLabel label = new ZpLabel();
					label.setLabelName(string);
					label.setLabelHeat(1);
					labelMapper.insert(label);
				}
			}
		}
	}

	@Override
	public List<ZpResources> selectDataList(QueryResForm query) {
		return this.baseMapper.selectDataList(query);
	}

	@Override
	@Transactional
	public int delById(Long[] ids) {
		return this.baseMapper.deleteBatchIds(Arrays.asList(ids));
	}

	@Override
	public int recommend(Long[] ids) {
		for (Long long1 : ids) {
			ZpResources byId = this.getById(long1);
			if (ToolUtil.isNotEmpty(byId)) {
				byId.setRec("1");
				this.baseMapper.updateById(byId);
			}
		}
		return 0;
	}

	@Override
	public int unrecommend(Long[] ids) {
		for (Long long1 : ids) {
			ZpResources byId = this.getById(long1);
			if (ToolUtil.isNotEmpty(byId)) {
				byId.setRec("0");
				this.baseMapper.updateById(byId);
			}
		}
		return 0;
	}

	@Override
	public Page<ZpResources> pageListHeats(int pageNum, int limit, ZpResources res) {
		Page<ZpResources> page = new Page<>(pageNum, limit);
		QueryWrapper<ZpResources> queryWrapper = new QueryWrapper<>();
		String city = res.getCity();
		if (StrUtil.isNotEmpty(city)) {
			queryWrapper.eq("city", city);
		}
		queryWrapper.orderByDesc("read_size", "vote_size");
		return this.page(page, queryWrapper);
	}

	@Override
	@Transactional
	public void timingPublish(Long id) {
		ZpResources res = this.getById(id);
		if (ToolUtil.isNotEmpty(res)) {
			res.setDraft("0");
			String timingTime = res.getTimingTime();
			DateTime parse = DateUtil.parse(timingTime);
			Instant instant = parse.toInstant();
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
			res.setUpdateTime(localDateTime);
			this.baseMapper.updateById(res);
		}
		SysJob byId = jobService.getById(id);
		if (ToolUtil.isNotEmpty(byId)) {
			try {
				jobService.deleteJob(byId);
			} catch (SchedulerException e) {
				log.error("移除定时任务异常:{}", e);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int publish(String id) {
		ZpResources byId = this.getById(id);
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("资源不存在！");
		}
		int row = 0;
		Long userId = byId.getUserId();
		Long loginUserId = SecurityUtils.getLoginUserId();
		if (!loginUserId.equals(userId)) {
			throw new CustomException("资源不存在！");
		}
		byId.setDraft("0");
		row = this.baseMapper.updateById(byId);
		SysJob job = jobService.getById(byId.getArticleId());
		if (ToolUtil.isNotEmpty(job)) {
			try {
				jobService.deleteJob(job);
			} catch (SchedulerException e) {
				log.error("移除定时任务失败：{}", e);
			}
		}
		return row;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int del(String id) {
		ZpResources byId = this.getById(id);
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("资源不存在！");
		}
		Long userId = byId.getUserId();
		Long loginUserId = SecurityUtils.getLoginUserId();
		if (!loginUserId.equals(userId)) {
			throw new CustomException("非法操作！");
		}
		int deleteById = this.baseMapper.deleteById(id);
		String draft = byId.getDraft();
		if (StrUtil.equals(draft, "3")) {
			SysJob job = jobService.getById(byId.getArticleId());
			if (ToolUtil.isNotEmpty(job)) {
				try {
					jobService.deleteJob(job);
				} catch (SchedulerException e) {
					log.error("移除定时任务失败：{}", e);
				}
			}
		}
		return deleteById;
	}

	@Override
	public int wxdel(String id, Long loginUserId) {
		ZpResources byId = this.getById(id);
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("资源不存在！");
		}
		Long userId = byId.getUserId();
		if (!loginUserId.equals(userId)) {
			throw new CustomException("非法操作！");
		}
		int deleteById = this.baseMapper.deleteById(id);
		String draft = byId.getDraft();
		if (StrUtil.equals(draft, "3")) {
			SysJob job = jobService.getById(byId.getArticleId());
			if (ToolUtil.isNotEmpty(job)) {
				try {
					jobService.deleteJob(job);
				} catch (SchedulerException e) {
					log.error("移除定时任务失败：{}", e);
				}
			}
		}
		return deleteById;
	}

	@Override
	public PublishRes wxadd(ResourcesForm resources) {
		ZpResources zpResources = new ZpResources();
		BeanUtil.copyProperties(resources, zpResources);
		this.wxwrap(zpResources);
		// 保存
		boolean save = this.save(zpResources);
		if (!save) {
			throw new CustomException("发布失败");
		}
		return PublishRes.builder().id(zpResources.getArticleId()).title(zpResources.getTitle())
				.draft(zpResources.getDraft()).build();
	}

	/**
	 * 数据封装
	 * 
	 * @param zpResources
	 */
	private void wxwrap(ZpResources zpResources) {
		String content = zpResources.getContent();
		String contentText = zpResources.getContentText();
		String title = zpResources.getTitle();
		String contentText2 = zpResources.getContentText();
		if (contentText2.length() >= 300) {
			zpResources.setRec("1");
		}
		// 经营业态
		Integer formatId = zpResources.getFormatId();
		if (ToolUtil.isNotEmpty(formatId) && formatId == -1) {
			zpResources.setFormatId(null);
		}
		// 区域站点
		String county = zpResources.getCounty();
		Integer columnId = zpResources.getColumnId();
		if (columnId != 1) {
			QueryWrapper<ZpCity> queryWrapper = new QueryWrapper<>();
			queryWrapper.like("name", county);
			queryWrapper.eq("level_type", "3");
			List<ZpCity> list = cityService.list(queryWrapper);
			if (ToolUtil.isNotEmpty(list)) {
				ZpCity city = list.get(0);
				String ancestors = city.getAncestors();
				String[] split = StrUtil.splitToArray(ancestors, ",");
				zpResources.setProvince(split[1]);
				zpResources.setCity(split[2]);
				zpResources.setCounty(city.getAid());
			} else {
				zpResources.setProvince("500000");
				zpResources.setCity("500100");
			}
		}
		String keystr = title;
		if (StrUtil.isNotBlank(contentText)) {
			// 文章摘要
			String summary = HanLP.getSummary(contentText, 130);
			zpResources.setSummary(summary);
			keystr += contentText;
		}

		// 关键词
		List<String> keyWordsList = HanLP.extractKeyword(keystr, 50);
		String keywords = StrUtil.sub(StrUtil.join(",", keyWordsList), 0, 500);
		zpResources.setKeywords(keywords);
		// 文章图片
		List<String> imgs = HtmlUtils.getImgs(content);

		// 文章视频
		List<String> videos = HtmlUtils.getVideo(content);
		if (ToolUtil.isNotEmpty(videos)) {
			if (videos.size() > 1) {
				throw new CustomException("最多上传一个视频");
			}
			zpResources.setVideoUrl(JSONObject.toJSONString(new HashSet<>(videos)));
			// 文章视频Etag
			List<String> videoEtag = HtmlUtils.getVideoEtag(content);
			if (ToolUtil.isNotEmpty(videoEtag)) {
				zpResources.setVideoEtag(JSONObject.toJSONString(new HashSet<>(videoEtag)));
			}

			// 文章视频
			List<String> coverVideos = HtmlUtils.getVideoPoster(content);
			if (ToolUtil.isNotEmpty(coverVideos)) {
				zpResources.setCoverVideo(coverVideos.get(0));
				zpResources.setPosters(JSONObject.toJSONString(new HashSet<>(coverVideos)));
			}
		} else if (ToolUtil.isNotEmpty(imgs)) {
			Set<String> hashSet = new HashSet<>(imgs);
			String bucketName = CrawlerConfig.getBucketName();
			if (hashSet.size() > 3) {
				List<String> pic = new ArrayList<>();
				int i = 0;
				for (String string : hashSet) {
					if (i > 3) {
						break;
					}
					String destImageFile = CrawlerConfig.getImgCoverPath() + IdUtil.simpleUUID() + ".jpg";
					String[] split = StrUtil.splitToArray(string, "/");
					String uploadPath = CrawlerConfig.getUploadPath();
					// 上传文件路径
					String fileName = uploadPath + File.separator + split[split.length - 1];
					if (ToolUtil.isNotEmpty(split) && FileUtil.isFile(fileName)) {
						ImgUtils.imgcompressloc(fileName, 200, 135, destImageFile);
					} else {
						ImgUtils.imgcompress(string, 200, 135, destImageFile);
					}
					String imgFileName = IdUtil.simpleUUID() + ".jpg";
					String imgkey = Constants.IMG_KEY + imgFileName;
					cosPutObject.localPut(destImageFile, bucketName, imgkey);
					pic.add(Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/" + Constants.IMG_KEY
							+ imgFileName);
					i++;
				}
				zpResources.setPictureSet(JSONObject.toJSONString(new HashSet<>(pic)));
			} else {
				String destImageFile = CrawlerConfig.getImgCoverPath() + IdUtil.simpleUUID() + ".jpg";
				String string = imgs.get(0);
				if(StrUtil.isNotBlank(string)) {
					String[] split = StrUtil.splitToArray(string, "/");
					String uploadPath = CrawlerConfig.getUploadPath();
					// 上传文件路径
					String fileName = uploadPath + File.separator + split[split.length - 1];
					if (ToolUtil.isNotEmpty(split) && FileUtil.isFile(fileName)) {
						ImgUtils.imgcompressloc(fileName, 200, 135, destImageFile);
					} else {
						ImgUtils.imgcompress(string, 200, 135, destImageFile);
					}
					String imgFileName = IdUtil.simpleUUID() + ".jpg";
					String imgkey = Constants.IMG_KEY + imgFileName;
					cosPutObject.localPut(destImageFile, bucketName, imgkey);
					zpResources.setCoverImage(Constants.HTTPS + bucketName + "." + CrawlerConfig.getDomainName() + "/"
							+ Constants.IMG_KEY + imgFileName); // 文章封面
				}
			}
		}

		if (columnId == 1) {
			// 发布站点
			zpResources.setCity(tokenService.getCitySite());
		}
	}

	@Override
	public Page<ZpResources> searchkey(Page<ZpResources> page, String keyword, List<String> ik) {
		if (StrUtil.isNotEmpty(keyword)) {
			QueryWrapper<ZpResources> queryWrapper = new QueryWrapper<>();
			queryWrapper.select("article_id", "title", "draft", "city");
			queryWrapper.eq("draft", "0").and(i -> i.eq("city", tokenService.getCitySite()));
			if (ToolUtil.isNotEmpty(ik)) {
				queryWrapper.and(i -> {
					for (String string : ik) {
						i.or().like("title", string);
					}
				});
			} else {
				queryWrapper.like("title", keyword);
			}
			queryWrapper.orderByDesc("update_time");
			return this.page(page, queryWrapper);
		}
		return new Page<>(1, 10);
	}

	@Override
	public Page<ZpResources> appsearch(Integer pageNum, Integer limit, String keyword, List<String> ik) {
		Page<ZpResources> page = new Page<>(pageNum, limit);
		if (StrUtil.isNotEmpty(keyword)) {
			QueryWrapper<ZpResources> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("draft", "0").and(i -> i.eq("city", tokenService.getCitySite()));
			if (ToolUtil.isNotEmpty(ik)) {
				queryWrapper.and(i -> {
					for (String string : ik) {
						i.or().like("title", string).or().like("summary", string).or().like("tags", string);
					}
				});
			} else {
				queryWrapper.like("title", keyword).or().like("summary", keyword).like("tags", keyword);
			}
			queryWrapper.orderByDesc("update_time");
			return this.page(page, queryWrapper);
		}
		return new Page<>(pageNum, limit);
	}

	@Override
	public Page<ZpResources> recType(Page<ZpResources> page, Long articleId, String keywords) {
		QueryWrapper<ZpResources> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("article_id", articleId);
		queryWrapper.eq("draft", "0");
		queryWrapper.orderByDesc("update_time");
		return this.page(page, queryWrapper);
	}

	@Override
	public Page<ZpResources> myCreatePageList(Page<ZpResources> page, QueryResForm query) {
		Long userId = query.getUserId();
		QueryWrapper<ZpResources> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", userId);
		queryWrapper.in("draft", Arrays.asList("0", "2", "3"));
		queryWrapper.orderByDesc("update_time");
		return this.page(page, queryWrapper);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public PublishRes wxupdate(SysUser user, ResourcesForm resources) {
		ZpResources byId = this.getById(resources.getArticleId());
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("更新的资源不存在失败");
		}
		Long userId = byId.getUserId();
		if (!userId.equals(user.getUserId())) {
			throw new CustomException("禁止操作");
		}
		ZpResources zpResources = new ZpResources();
		BeanUtil.copyProperties(resources, zpResources);
		this.wxwrap(zpResources);
		boolean updateById = this.updateById(zpResources);
		if (!updateById) {
			throw new CustomException("更新失败");
		}
		addTags(zpResources.getTags());
		SysJob job = jobService.getById(byId.getArticleId());
		if (ToolUtil.isNotEmpty(job)) {
			try {
				jobService.deleteJob(job);
			} catch (SchedulerException e) {
				log.error("移除定时任务失败：{}", e);
			}
		}
		return PublishRes.builder().id(zpResources.getArticleId()).title(zpResources.getTitle())
				.draft(zpResources.getDraft()).build();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int wxpublish(SysUser user, String id) {
		ZpResources byId = this.getById(id);
		if (ToolUtil.isEmpty(byId)) {
			throw new CustomException("资源不存在！");
		}
		int row = 0;
		Long userId = byId.getUserId();
		Long loginUserId = user.getUserId();
		if (!loginUserId.equals(userId)) {
			throw new CustomException("资源不存在！");
		}
		byId.setDraft("0");
		row = this.baseMapper.updateById(byId);
		SysJob job = jobService.getById(byId.getArticleId());
		if (ToolUtil.isNotEmpty(job)) {
			try {
				jobService.deleteJob(job);
			} catch (SchedulerException e) {
				log.error("移除定时任务失败：{}", e);
			}
		}
		return row;
	}

	@Override
	public Page<ZpResources> apiPageList(Page<ZpResources> page, String rec, Integer i) {
		return this.lambdaQuery()
				.select(
						ZpResources::getArticleId,
						ZpResources::getTitle,
						ZpResources::getContent,
						ZpResources::getCoverImage,
						ZpResources::getCoverVideo,
						ZpResources::getPictureSet,
						ZpResources::getVideoUrl,
						ZpResources::getPosters,
						ZpResources::getReadSize,
						ZpResources::getUserId,
						ZpResources::getRec,
						ZpResources::getCreateTime,
						ZpResources::getUpdateTime
						)
				.eq(ZpResources::getRec, rec)
				.eq(ZpResources::getColumnId, i)
				.eq(ZpResources::getDraft, "0")
				.orderByDesc(ZpResources::getUpdateTime)
				.page(page);
	}
}
